﻿using System;
using System.Data;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ProgramMain.Database;

namespace ProgramMain.Framework
{
    public partial class BaseModalDetailCtl : ProgramMain.Framework.BaseDetailCtl
    {
        private BindingSource m_dataSource = null;
        public BindingSource dataSource
        {
            get
            {
                return m_dataSource;
            }
            set
            {
                m_dataSource = value;
            }
        }

        public bool AutoClose { get; set; }

        public enum ShowModeTypes {Add, View, Edit, Delete};
        protected ShowModeTypes m_ShowMode = ShowModeTypes.View;
        public ShowModeTypes ShowMode
        {
            get
            {
                return m_ShowMode;
            }
        }

        private DataRowView m_CurrentRowView = null;
        public DataRowView CurrentRowView
        {
            get
            {
                return m_CurrentRowView;
            }
        }

        private bool m_bOnActionClose = false;

        public BaseModalDetailCtl()
        {
            InitializeComponent();
        }

        private string _saveCaption;
        public string SaveCaption
        {
            get { return btnSave.Text; }
            set { _saveCaption = value; }
        }

        public DialogResult ShowModal(ShowModeTypes pShowMode)
        {
            m_ShowMode = pShowMode;

            this.btnSave.Enabled = m_ShowMode != ShowModeTypes.View;
            string Caption;
            if (m_ShowMode == ShowModeTypes.Add)
                Caption = "Добавление";
            else if (m_ShowMode == ShowModeTypes.Edit)
                Caption = "Изменение";
            else if (m_ShowMode == ShowModeTypes.View)
                Caption = "Просмотр";
            else
                Caption = "Удаление";
            if (!string.IsNullOrEmpty(_saveCaption))
                this.btnSave.Text = _saveCaption;
            else if (m_ShowMode == ShowModeTypes.Delete)
            {
                this.btnSave.Text = "Удалить";
            }
            return ProgramMain.Framework.frmBaseModal.ShowModal(this, Caption, this.btnSave, this.btnCancel);
        }

        override public void OnLoadControl(object sender, EventArgs e)
        {
            if (this.ParentForm != null)
            {
                this.ParentForm.FormClosed += new FormClosedEventHandler(this.FrmCommon_FormClosed);
                this.ParentForm.FormClosing += new FormClosingEventHandler(this.FrmCommon_FormClosing);
            }

            if (this.dataSource != null)
            {
                m_CurrentRowView = (DataRowView) this.dataSource.Current;

                this.BindDataControls();
            }

            try
            {
                this.InitializeDataControls();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Непредвиденная ошибка во время чтения данных!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            if (ShowMode == ShowModeTypes.View || ShowMode == ShowModeTypes.Delete)
                DisableLayoutControls();

            if (AutoClose)
            {
                if (this.dataSource != null) dataSource.EndEdit();
                btnSave.PerformClick();
            }  
        }

        protected virtual void BindDataControls()
        {
        }

        public virtual bool CheckValidation()
        {
            return true;
        }
        protected virtual void InitializeDataControls()
        {
        }

        public virtual void btnSave_Click(object sender, EventArgs e)
        {
            if (m_ShowMode == ShowModeTypes.Delete)
            {
                if (this.dataSource != null)
                {
                    CurrentRowView.Row["UserID"] = ProgramMain.Framework.BaseSecurity.UserID;
                    this.dataSource.RemoveCurrent();
                }
            }
            else
            {
                if(!CheckValidation() ) return;
                if (!dxValidationProvider.Validate())
                {
                    foreach (Control c in dxValidationProvider.GetInvalidControls())
                    {
                        DevExpress.XtraEditors.DXErrorProvider.ValidationRuleBase rule =
                            dxValidationProvider.GetValidationRule(c);
                        XtraMessageBox.Show(rule.ErrorText);
                        c.Focus();
                        return;
                    }
                }

                if (this.dataSource != null)
                {
                    CurrentRowView.Row["UserID"] = ProgramMain.Framework.BaseSecurity.UserID;
                    this.dataSource.EndEdit();
                    
                }
            }

            m_bOnActionClose = true;

            if (this.ParentForm != null)
                this.ParentForm.Close();
        }

        protected void DisableLayoutControls()
        {
            foreach(Control ctl in this.layoutPanelControl.Controls)
            {
                ctl.Enabled = false;
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            m_bOnActionClose = true;
            
            if (m_ShowMode == ShowModeTypes.Add || m_ShowMode == ShowModeTypes.Edit)
            {
                if (this.dataSource != null)
                    this.dataSource.CancelEdit();
            }
            if (this.ParentForm != null)
                this.ParentForm.Close();
        }

        public void FrmCommon_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (!m_bOnActionClose)
            {
                m_bOnActionClose = true;

                if (m_ShowMode == ShowModeTypes.Add || m_ShowMode == ShowModeTypes.Edit)
                {
                    if (this.dataSource != null)
                        this.dataSource.CancelEdit();
                }
            }
        }

        public void FrmCommon_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.ParentForm != null)
            {
                if (m_ShowMode == ShowModeTypes.Add || m_ShowMode == ShowModeTypes.Edit)
                {
                    e.Cancel = this.ParentForm.DialogResult != DialogResult.Cancel
                               && !dxValidationProvider.Validate();
                }
            }
        }
    }
}
